package com.xhl.browser.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.xhl.browser.domain.Msg;
import com.xhl.browser.support.SimpleResponse;
import com.xhl.core.properties.base.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 徐宏亮
 * @description
 * @date 2019/3/4 19:33
 */
@Controller
public class BrowserSecurityController {
    /**
     * 能够取到当前请求，在 Session 中
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     * 跳转操作
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 功能描述 当需要身份验证时，跳转到这里
     * @author 徐宏亮
     * @date 2019/3/4 19:35
     * @param request
     * @param response
     * @return java.lang.String
     */
    @ResponseBody
    @GetMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)//返回 401 状态码
    public SimpleResponse requireAuthtication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        //根据判断的结果返回不同的内容
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            StaticLog.info("引发跳转的请求是：" + redirectUrl);
            if (StrUtil.endWithIgnoreCase(redirectUrl, ".html")) {
                StaticLog.info("重定向的路径是：" + securityProperties.getBrowser().getLoginPage());
                //重定向
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
            }
        }
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登陆页。");
    }

    @ResponseBody
    @GetMapping("/me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }

    @GetMapping("/")
    public String test(Model model) {
        Msg msg = new Msg("测试标题", "测试内容", "额外信息，只对管理员显示");
        model.addAttribute("msg", msg);
        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }
}
